package com.vitas.coin.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.vitas.coin.task.SilentTask;
import com.vitas.coin.task.TaskEngine;


abstract class MyBaseDao {

    MyBaseDao() {

    }

    public void doInBackground(Runnable r) {
        SilentTask task = new SilentTask(getClass().getSimpleName()) {
            @Override
            public void runInBackground() {
                r.run();
            }
        };
        TaskEngine.getInstance().submit(task);
    }

    protected synchronized SQLiteDatabase getDataBase() {
        return DatabaseManager.getInstance().openDatabase();
    }

    protected synchronized void closeDataBase() {
        DatabaseManager.getInstance().closeDatabase();
    }

    protected void closeCursor(Cursor c) {
        if (c != null && !c.isClosed()) {
            try {
                c.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    protected abstract String getTableName();

    public boolean delete(long id) {
        SQLiteDatabase db = null;
        try {
            db = getDataBase();
            int result = db.delete(getTableName(), "id=?", new String[]{String.valueOf(id)});
            return result == 1;
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                closeDataBase();
            }
        }
        return false;
    }

    public void delete(final long id, DBListener listener) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                boolean bo = delete(id);
                if (listener != null) {
                    listener.onResult(bo, "", null);
                }
            }
        });
    }

    public long allCaseNum() {
        SQLiteDatabase db = null;
        try {
            db = getDataBase();
            if (db == null) {
                return 0;
            }
            return allCaseNum(db);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                closeDataBase();
            }
        }
        return 0;
    }

    public long allCaseNum(SQLiteDatabase db) {
        Cursor cursor = null;
        try {
            String sql = "select count(*) from " + getTableName();
            cursor = db.rawQuery(sql, null);
            cursor.moveToFirst();
            long count = cursor.getLong(0);
            return count;
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }
        return 0;
    }
}
